// initial state
const state = () => ({
    userToken: LocalStorage.get(USER_TOKEN) || '',
    userInfo: LocalStorage.get(USER_INFO) || {},
})

// getters
const getters = {
    userInfo: (state, getters) => {
        return state.userInfo
    },
    userToken: (state, getters) => {
        return state.userToken
    }
}

// actions
const actions = {
    async saveUser({commit, state}, userInfo) {
        // alert(JSON.stringify(userInfo))
        commit('setUserTokenToVuex', userInfo.token)
        commit('setUserInfoToVuex', userInfo)
    },
}

// mutations
const mutations = {
    /**
     * 保存 token 到 vuex
     */
    setUserTokenToVuex(state, userToken) {
        state.userToken = userToken
        this.commit('user/saveToken');
    },

    /**
     * 保存 token 到 本地存储
     */
    saveToken(state) {
        LocalStorage.set(USER_TOKEN, state.userToken)
    },

    /**
     * 保存 userInfo 到 vuex
     */
    setUserInfoToVuex(state, userInfo) {
        state.userInfo = userInfo
        this.commit('user/setUserInfo');
    },

    /**
     * 保存 userInfo 到 本地存储
     */
    setUserInfo(state) {
        LocalStorage.set(USER_INFO, state.userInfo)
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
}
